package com.vic.filedb.mongo.controller;

import com.vic.filedb.mongo.common.exception.FileServerException;
import com.vic.filedb.mongo.entity.File;
import com.vic.filedb.mongo.service.FileService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
@RequestMapping(value = "/file")
public class FileController {

    @Resource
    private FileService fileService;

    @PostMapping(value = "/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) throws FileServerException {
        return fileService.upload(file);
    }

    @GetMapping(value = "/{imageId}")
    public ResponseEntity<Object> getImageById(@PathVariable(value = "id") String fileId) throws FileServerException {
        File image = fileService.getFileById(fileId);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "fileName=\"" + image.getName() + "\"")
                .header(HttpHeaders.CONTENT_TYPE, image.getContentType())
                .header(HttpHeaders.CONTENT_LENGTH, image.getSize() + "")
                .header("Connection", "close")
                .body(image.getContent());

    }
}
